// Package service /*php-fpm
package service

import (
	"strings"

	cf "godocker/common/functions"
)

type phpFpm struct {
	SName string

	basicDir []string
	name     string
	version  string
}

func phpNew() *phpFpm {
	dir := installDir + "/lib/php-fpm"
	return &phpFpm{
		"php-fpm",
		[]string{
			installDir + "/worker/php",
			dir + "/conf",
			dir + "/log",
		},
		cf.GetEnvVal(installDir+"/.env", "fpmname="),
		cf.GetEnvVal(installDir+"/.env", "fpmv="),
	}
}

func (p phpFpm) install() {
	p.mkdir()
	p.setDockerFile()
	p.dockerPull()
}

func (p phpFpm) mkdir() {
	for i := 0; i < len(p.basicDir); i++ {
		cf.MakeDir(p.basicDir[i])
	}
}

func (p phpFpm) setDockerFile() {
	str := cf.GetDockerfile("Dockerfile-php-fpm")

	newStr := strings.Replace(str, "{$version}", p.version, -1)

	cf.WriteToFileTrunc(ymlDir+"/Dockerfile-php-fpm", newStr)
}

func (p phpFpm) dockerPull() {
	cf.ExecShell("docker run --name " + p.name + " -dp 9000:9000 php:" + p.version)
	cf.ExecShell("docker cp " + p.name + ":/usr/local/etc/. " + p.basicDir[1])
	cf.ExecShell("docker stop " + p.name)
	cf.ExecShell("docker rm " + p.name)
}
